package com.juyu.miliao.authentication.security;

import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.security.exception.ThirdPartyLoginException;
import com.juyu.miliao.common.util.IpUtil;
import com.juyu.miliao.common.util.VerifyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 第三方登录
 *
 * @author wbf
 */
public class ThirdPartyLoginFilter extends AbstractAuthenticationProcessingFilter {
    private final Logger logger = LoggerFactory.getLogger(ThirdPartyLoginFilter.class);

    public ThirdPartyLoginFilter(String filterProcessesUrl) {
        super(new AntPathRequestMatcher(filterProcessesUrl, "POST"));
    }

    public ThirdPartyLoginFilter() {
        super(new AntPathRequestMatcher("/login/thirdParty", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String access_token = request.getParameter("access_token");
        if (access_token == null || access_token.equals(""))
            throw new ThirdPartyLoginException("access_token:" + access_token);
        String openid = request.getParameter("openid");
        if (openid == null || openid.equals(""))
            throw new ThirdPartyLoginException("openid:" + openid);
        //type登录类型：1QQ 2微信
        String type = request.getParameter("type");
        if (type == null)
            throw new ThirdPartyLoginException("type:" + type);
        type = type.trim();
        if (!type.matches("[1,2]"))
            throw new ThirdPartyLoginException("type:" + type);

        CommonHead com = VerifyUtil.verifyCommonHead(request);

        //获取ip
        String ip = IpUtil.getIPv4Address(request);
        logger.info("请求头信息:[{}]",com);
        logger.info("参数打印：access_token={},openid={},type ={},channel ={}", access_token, openid, type, com.getChannel());
        ThirdPartyLoginToken authRequest = new ThirdPartyLoginToken(openid, "", access_token, Integer.parseInt(type), ip, com);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

}
